class Solution:
    def licenseKeyFormatting(self, S: 'str', K: 'int') -> 'str':
        import re

        S = S.upper()
        available_char_count = len(S) - S.count('-')

        if available_char_count <= K:
            return S.replace('-', '')

        groups = S.split('-')
        chars = ''.join(groups)
        res_groups = []

        head_len = available_char_count % K
        (head_len > 0) and res_groups.append(chars[0:head_len])
        res_groups.extend(re.findall(r'.{' + str(K) + r'}', chars[head_len:]))

        return '-'.join(res_groups)


s = Solution()
print(s.licenseKeyFormatting("2-4A0r7-4k", 4))
print(s.licenseKeyFormatting("---", 3))
print(s.licenseKeyFormatting("5F3Z-2e-9-w", 4))
print(s.licenseKeyFormatting("2-5g-3-J", 2))